package com.itheima.text6;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TCPSocket {
    public static void main(String[] args) throws IOException {
        File file = getJpgFile();

        Socket socket = new Socket("192.168.23.64", 10006);

        //创建流 读取文件数据
        BufferedInputStream bis = new BufferedInputStream
                (new FileInputStream(file));

        //获取输出流  将数据发送服务器
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        //读写
        int len;
        byte[] bytes = new byte[1024];
        while ((len = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, len);
            bos.flush();//s刷新
        }
        socket.shutdownOutput();


        BufferedReader br = new BufferedReader
                (new InputStreamReader(socket.getInputStream()));

        String str = br.readLine();

        System.out.println(str);


    }

    // 获取jpg图片文件的方法
    private static File getJpgFile() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个JPG格式图片文件的路径：");
        while (true) {
            File file = new File(sc.nextLine());
            if (!file.exists()) {
                System.out.println("该文件路径不存在，请重新输入：");
            } else if (file.isDirectory()) {
                System.out.println("您输入的是一个文件夹路径，请重新输入：");
            } else if (file.getName().endsWith(".jpg") || file.getName().endsWith(".JPG")) {
                return file;
            } else {
                System.out.println("您输入文件格式有误，请重新输入");
            }
        }
    }
}
